import path from "path";
import fs from "fs/promises";
import { fileURLToPath } from "url";

export default async function (app) {
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
  // 从 apis 目录向上两级到达项目根目录，然后进入 uploads 目录
  const uploadDir = path.join(__dirname, "..", "..", "uploads");

  // 删除文件接口
  app.delete("/:filename", async (request, reply) => {
    try {
      const { filename } = request.params;

      // 验证文件名格式，防止路径遍历攻击
      if (!/^[\w\-]+\.(jpg|jpeg|png|gif|webp)$/.test(filename)) {
        return reply.code(400).send({
          success: false,
          message: "无效的文件名格式",
        });
      }

      const filePath = path.join(uploadDir, filename);

      console.log(">>>", filePath);

      // 检查文件是否存在
      try {
        await fs.access(filePath);
      } catch {
        return reply.code(404).send({
          success: false,
          message: "图片不存在",
        });
      }

      // 执行删除操作
      await fs.unlink(filePath);

      return {
        success: true,
        message: "图片已成功删除",
        filename,
      };
    } catch (error) {
      app.log.error("删除图片失败:", error);
      return reply.code(500).send({
        success: false,
        message: "服务器错误，删除图片失败",
      });
    }
  });
}
